//热搜
var express = require('express');
var router = express.Router();
var mongoose = require("../../mongoose")

//创建产品Schema
var schema = new mongoose.Schema({
    id: { type: String, require: true },//id
    name: { type: String, require: true },//搜索名
    num: { type: Number, require: true },//搜索次数

});
// 定义MongoDB数据模型 (表>=集合)
var Searchlists = mongoose.model("searchlists", schema);
// 生成id
var get_id_string = require('../../utils/setId')

router.post('/search', async function (req, res, next) {

    let body = {
        name: req.body.name,
    }
    const data = await Searchlists.find().where({
        name: body.name
    })

    if (req.body.name !== '') {// 判空
        if (data.length == 0) {  // ==0代表数据库没有这个词 所以需要创建
            body.id = get_id_string() //创建id
            body.num = 1 // 第一次搜索 搜索初始次数为1
            //插入数据
            await Searchlists.create(body)
        } else {//如果数据库有这个词 就直接去更改搜索次数 
            let num = data[0].num + 1
            await Searchlists.updateOne({
                name: body.name
            }, {
                $set: {
                    num: num,
                },
            })
        }
    }

    res.send({
        code: 200,
        msg: "请求成功",
        success: true,
    })

})
router.get('/search/list', async function (req, res, next) {
    await Searchlists.find().sort({
        num: -1
    }).limit(5).then((data) => {
        res.send({
            code: 200,
            success: true,
            msg: "列表查询成功",
            data,
        })
    }).catch((err) => {
        res.send({
            code: 500,
            success: false,
            msg: "列表查询失败",
            data: err
        })
    });

})
module.exports = router;

